NB: This demonstration analysis was performed on unpublished development data. This experiment was designed to investigate the effect of pH on driving RNP enrichment to the interphase of a phenol chloroform preparation.
Aims:
A. To test the effects of pH manipulation on concentrating RBP-RNA complexes to the interphase of a customised Phenol-Chloroform Cocktail
B. To compare these results with past studies
Method:
See associated writeup for Expt.295
Custom Functions
jwrangle.importMixedFiles( )
I generally import everything I MIGHT use at the start and set up pathing using the OS-agnostic pathlib.
#### File utilities
import os
import pandas as pd
from pathlib import Path
from imp import reload
#### Data Wrangling
import copy
import numpy as np
#### RBP Suite Modules
import jwrangle
import jvis
import jinspect
import jtest
import jweb
#### Sequence Tools
from Bio import SeqIO
#### Graphical Packages
import upsetplot as upset
import seaborn as sns
import matplotlib.pyplot as plt
import altair as alt
#### define working directories
cwd = Path(os.getcwd())
base_path = Path(os.path.join(*cwd.parts[:cwd.parts.index('experiments')]))
#### MaxQuant proteinGroups & evidence files
MQ_folder = jwrangle.importMixedFiles(cwd / 'MaxQuant')
MQ_folder.keys()
pGroups = MQ_folder['proteinGroups.txt']
evidence = MQ_folder['evidence.txt']
#### Inspect MQ setup
MQ_folder['parameters.txt'].head(9)
Custom Functions
jwrangle.MQ_writeMetadata( )
Metadata tabulates the test conditions for ALL experiments that shared the same MQ search and thuss all experiments that comprise the MQ outputs. Metadata can also be done in a spreadsheet program. Here, I have created my metadata programmatically instead (I simply find this easier).
The metadata table gives users the opportunity to rename samples and define the experimental parameters for the data. This task can be expecially complex for MaxQuant because a unified output is generated even if distinctly separate experiments are searched as a batch and with different parameters applied.
The function jwrangle.MQ_writeMetadata( ) will take a metadata table, rename all samples in the proteinGroups and evidence files, assign alternative filenames, and save new copies to be used in future analyses.
#### Inspect column names
colnames = list(pGroups.columns.values)
#### Derive experiment names as a list
#### The instrument and MQ have assigned some irritating notation to the samples
experiment_names = []
for i in colnames:
if 'Intensity ' in i:
experiment_names.append(i.replace('Intensity ', ''))
#### Create a list of associated conditions
#### These samples were mislabeled 'NC' and 'PC' (the latter is often short for PAR-CL, but these samples are 254nm crosslinked)
#### The pH on these samples needs to be corrected)
condition = []
for i in experiment_names:
trim = i.split('-')[0]
pref = trim.split('_')[2] + '_' + trim.split('_')[3]
if 'NC' in pref:
pref = pref.replace('NC','nCL')
else:
pref = pref.replace('PC','254')
if 'pH4' in pref:
pref = pref.replace('pH4OdT','pH4.5')
elif 'pH5' in pref:
pref = pref.replace('pH5OdT','pH5.5')
elif 'pH8' in pref:
pref = pref.replace('pH8OdT','pH7.8')
condition.append(pref)
#### Create a list of associated replicate identifiers
replicate = []
for i in experiment_names:
replicate.append(i.split('-')[-1])
#### Create a more reader friendly list of sample names
samples = []
for i in experiment_names:
pref = i.split('_')[0]
name_clean = i.replace(pref+'_','')
if len(name_clean.split('_')[0])==1:
newprefix = '0' + name_clean.split('_')[0]
name_clean = newprefix + '_' + name_clean.split('_',1)[1]
if 'NC' in name_clean:
name_clean = name_clean.replace('NC','nCL')
else:
name_clean = name_clean.replace('PC','254')
if 'pH4' in name_clean:
name_clean = name_clean.replace('pH4OdT','pH4.5')
elif 'pH5' in name_clean:
name_clean = name_clean.replace('pH5OdT','pH5.5')
elif 'pH8' in name_clean:
name_clean = name_clean.replace('pH8OdT','pH7.8')
samples.append(name_clean)
#### The MQ_groups dictionary assigns each condition to its MQ group parameter
MQ_groups = {'pH4.5':['pH4.5_nCL','pH4.5_254'],
'pH5.5':['pH5.5_nCL','pH5.5_254'],
'pH7.8':['pH7.8_nCL','pH7.8_254']}
#### We then use the condition list to create an MQ_groups list
Grp_parameters = []
for label in condition:
for key, value in MQ_groups.items():
if label in value:
Grp_parameters.append(key)
expt_df = pd.DataFrame(
{'experiment': experiment_names,
'condition': condition,
'replicate': replicate,
'sample':samples,
'measure':['Intensity']*len(samples), # adding this column allows our metadata file to be compatible with Proteus
'MQgroups':Grp_parameters
})
expt_df
#### Write the modified proteins Groups and evidence files to a local folder
MQ_expt295 = jwrangle.MQ_writeMetadata(pGroups, evidence, expt_df, 'e295', cwd)
Functions
jweb.mapAnyID( )
jwrangle.importMixedFiles( )
MaxQuant does a good job of assigning a Gene name to each protein group. Presumably these gene names come from the FASTA. However:
To avoid these problems we will remap the Majority protein IDs to ENTREZ gene IDs. jweb.mapAnyID( ) will retrieve all possible genes for each protein group, and will also select a primary ID to singularly represent the group by a consistent method. This is a very flexible function, see help( ) for further explanation. From this point, the MQ 'Gene names' column will no longer be necessary. This function can also handle ID mapping to and from almost any convention.
Ensuring our proteins have a consistent gene naming strategy is essential for inter-experiment comparison and the later use of set methods. It also creates a standard that can be applied for accurately mapping RNA-Seq results and thus aid in future mapping of protein-RNA partners.
#### If not already loaded, read in the metadata-adjusted files
metadata = pd.read_csv(cwd / 'metadata' / 'e295_metadata.csv', index_col = 0)
pGroups = pd.read_csv(cwd / 'MaxQuant' / 'e295_proteinGroups_metalabeled.txt', delimiter = '\t')
evidence = pd.read_csv(cwd / 'MaxQuant' / 'e295_evidence_metalabeled.txt', delimiter = '\t')
#### Dynamically remap gene names in our proteinGroups file and save a copy
# pGroups_remap = jweb.mapAnyID_gPro(pGroups['Majority protein IDs'].tolist(), splitstr = [';', '-'], geneProductType = 'protein',
# gConvertOrganism = 'hsapiens', gConvertTarget = 'ENTREZGENE', writetopath = [cwd, 'pGroups_remap'], writeTargetsAsList = 'NO')
#### If not already loaded, read in the remapped proteinGroups file
pGroups_remap = jwrangle.importMixedFiles(cwd / 'downloads' / 'pGroups_remap', dropSuffix = 'yes')
pGroups_remap.keys()
#### jwrangle.importMixedFiles() returns a dictionary where keys = files. We want the 'id_map' table created by jweb.mapAnyID_gPro().
#### We'll rename the Query column and drop duplicates so the table can be merged with our proteinGroups table.
id_map = pGroups_remap['id_map'].rename(columns={'Query': 'Majority protein IDs'}).drop_duplicates()
id_map.head(2)
#### Now use merge to add these new columns to our proteinGroups table
pGroups_map = pd.merge(pGroups, id_map, on='Majority protein IDs', how='left')
#### Check the tables are merged by viewing column elements from each.
pGroups_map[id_map.columns.tolist() + ['Peptide IDs']].head(2)
Functions
jinspect.MQ_getContaminants( )
MQ_getContaminants_sbplot( )
jwrangle.importMixedFiles( )
We can extract the conaminants from our proteinGroups file using jinspect.MQ_getContaminants( ). These extracted table will return log2(iBAQ values).
Contaminants can then be reviewed with _MQ_getContaminantssbplot( ).
#### Extract contaminants
contaminants = jinspect.MQ_getContaminants(pGroups_map, metadata)
contaminants.head(2)
#### Sort the metadata into a more intuitive order
metadata_sort = metadata.sort_values(by = ['MQgroups','sample'])
#### Visually inspect contaminants
jvis.MQ_getContaminants_sbplot(contaminants, metadata_sort, width = 1, length = 2, layout = 'individual')
The contaminant profiles of pH 4/8 are similar with a high concentration falling in their respective 254 fractions.
Strangely the contaminant profile of all nCL and 254 samples in the pH5 fraction are similar.
Not sure what to make of this with regard to sample processing but it can be reviewed in the repeat of this experiment, expt.297
Functions
jinspect.MQ_getMissedCleavages( )
jvis.CommonPalettesAsHex
jvis.BarPlotByGroup_sbplot( )
Assessing missed cleavages is an essential metric for understanding the quality of the tryptic digestion. This data is recorded in the evidence file.
_jinspect.MQgetMissedCleavages( ) will return a long form data table that can easily be used for plotting.
The dictionary jvis.CommonPalettesAsHex contains a number of palettes that are common to both matplotlib and ggplot (from R). These are provided to ensure consistency is easy to achieve across both languages.
We'll plot the missed cleavages with the generic function jvis.BarPlotByGroup_sbplot( )
#### Extract the missed cleavage data into a long form table for plotting
MissedCleavages = jinspect.MQ_getMissedCleavages(evidence, metadata, drop_contaminants = True)
MissedCleavages.sort_values(by=['expt','sample'], inplace = True)
MissedCleavages
### Select a colour palette
cpal = jvis.CommonPalettesAsHex
set2_paired = []
for i in cpal['Set2_qual']:
set2_paired.append(i)
set2_paired.append(i)
#### Plot the grouped data points
sns.set_style('whitegrid')
jvis.BarPlotByGroup_sbplot(MissedCleavages, x_col = 'group', y_col = '% Missed Cleavages', title = '% Missed Cleavages', pal = set2_paired)
Digestion efficiency isn't great. Let's reduce the digestion volume by 0.5x and maintain the same trypsin concentration in future experiments
Functions
jwrangle.MQ_getThreePassFilter( )
SeqIO.parse( )
After QC we no longer want the contaminants in our data. jwrangle.MQ_getThreePassFilter( ) will remove reverse peptides, contaminants, and only identified by site from MQ tables.
The filter will also accept customised exclusion lists in case users have added odd protein species to the search FASTA tables. In this particular experiment we added to the human FASTA, RNAse proteins and the large T antigen. The former as 1) a check that dynamic range is not being overwhelmed and 2) as an quantitative spike-in control to compare tryptic efficiency and the sample recovery across samples following C18 cleanup.
#### Map the location of the custom FASTA elements
os.listdir(base_path / 'my_resources' / 'FASTA')
#### Create a list of the non-human proteins that were added to the custom FASTA genome search.
new_cont = []
with open(base_path / 'my_resources' / 'FASTA' / "custom_proteome_elements.fasta", "r") as handle:
for record in SeqIO.parse(handle, "fasta"):
new_cont.append(record.id.split('|')[1])
#### Remove all unwanted contaminants and IDs from the proteinGroups table
pGroup_clean = jwrangle.MQ_getThreePassFilter(pGroups_map, custom_exclusion = new_cont)
#### Inspect the cleaned dataframe
pGroup_clean[['ENTREZGENE_gPro primary'] + [i for i in pGroup_clean.columns if 'iBAQ' in i]].head(2)
Functions
jinspect.MQ_dropDuplicateIDs( )
The next step focuses on improving confidence in the quality of our data. This is done by applying jinspect.MQ_dropDuplicateIDs( ) which has the below effects:
#### Drop duplicates and apply LFQ filter
filter_dict = jinspect.MQ_dropDuplicateIDs(pGroup_clean, metadata, prefix = 'Peptides', ID = 'ENTREZGENE_gPro primary', pool = 'measure', drop_ID = 'None',
keep_PoolCalcs = False, applyLFQ_filter = ['Intensity', 'iBAQ'])
#### Inspect filter dictionary
filter_dict.keys()
#### The df_keep value contains our targets, df_droprows conatins the discarded duplicates. Assign the df_keep value to a new variable and inspect.
pGroup_filtered = filter_dict['df_keep']
pGroup_filtered.head(2)
Functions
jtest.getDistanceMatrix( )
jvis.MQ_showDendrogramQC_mplplot( )
A distance matrix function jtest.getDistanceMatrix( ) is provided for users who wish to apply different algorithms or create different visualisations.
I like the 'ward' method for distance calculations and using a dengrogram to confirm that clustering matches expectations and so use a prerolled function jvis.MQ_showDendrogramQC_mplplot( )
#### Confirm that clustering matches expectations
jvis.MQ_showDendrogramQC_mplplot(pGroup_filtered, 'LFQ intensity', metadata, 'QC clustering: ', grid = 'YES', fsize = (8, 8))
Clustering reveals expected results
Functions
jwrangle.Log2_ByPrefix( )
jwrangle.MQ_poolMulti( )
jvis.ViolinCompare_sbplot( )
Here we review normalisation effects on each sample within the condition groups; these are most easily interpreted after log2 transformation. We will transform all measures of interest with _jwrangle.Log2ByPrefix( ) and then pool all the values of interest, by condition, with _jwrangle.MQpoolMulti( ). The function _jvis.ViolinComparesbplot( ) will let use compare Intensity distribution on a per sample basis.
Normalisation is applied to LFQ values by MaxQuant and is a feature of its handling of label-free data. I've not seen a detailed explanation of how it works though so it is a leap of faith that Cox and Mann have selected an appropriate method.
Normalisation must be applied separately to nCL and cCL groups. This is unusual though necessary to avoid outrageous results caused by having groups with extreme differences. See expt.313 for evidence.
#### Log2 transform available intensity values.
pGroup_log2 = jwrangle.Log2_ByPrefix(pGroup_filtered, 'LFQ intensity')
pGroup_log2 = jwrangle.Log2_ByPrefix(pGroup_log2, 'iBAQ')
pGroup_log2 = jwrangle.Log2_ByPrefix(pGroup_log2, 'Intensity')
pGroup_log2.replace(0,np.nan, inplace=True)
#### Create a long form dataset for each desired grouping
pool_SampleIntensity = jwrangle.MQ_poolMulti(pGroup_log2, metadata, melt_list = ['Intensity', 'LFQ intensity'], group = 'condition')
pool_SampleIntensity.keys()
#### Inspect the Intensity shifts generated by the LFQ normalisation algorithm. In MaxQuant Raw Intensity and iBAQ values are
#### not subjected to the LFQ normalisation calculations so this is a good way to spot any gross violations
sns.set_style('whitegrid')
jvis.ViolinCompare_sbplot(pool_SampleIntensity['pH4.5_nCL'], title = 'pH4.5 nCL: Normalisation Effects', ylabel = 'Log2(Intensity)', palette = ['#ff6666', '#99ccff'])
#### Inspect the Intensity shifts generated by the LFQ normalisation algorithm. In MaxQuant Raw Intensity and iBAQ values are
#### not subjected to the LFQ normalisation calculations so this is a good way to spot any gross violations
sns.set_style('whitegrid')
jvis.ViolinCompare_sbplot(pool_SampleIntensity['pH5.5_nCL'], title = 'pH5.5 nCL: Normalisation Effects', ylabel = 'Log2(Intensity)', palette = ['#ff6666', '#99ccff'])
#### Inspect the Intensity shifts generated by the LFQ normalisation algorithm. In MaxQuant Raw Intensity and iBAQ values are
#### not subjected to the LFQ normalisation calculations so this is a good way to spot any gross violations
sns.set_style('whitegrid')
jvis.ViolinCompare_sbplot(pool_SampleIntensity['pH7.8_nCL'], title = 'pH7.8 nCL: Normalisation Effects', ylabel = 'Log2(Intensity)', palette = ['#ff6666', '#99ccff'])
jvis.ViolinCompare_sbplot(pool_SampleIntensity['pH4.5_254'], title = 'pH4.5 254: Normalisation Effects', ylabel = 'Log2(Intensity)', palette = cpal['Set3_qual'])
jvis.ViolinCompare_sbplot(pool_SampleIntensity['pH5.5_254'], title = 'pH5.5 nCL: Normalisation Effects', ylabel = 'Log2(Intensity)', palette = cpal['Set3_qual'])
jvis.ViolinCompare_sbplot(pool_SampleIntensity['pH7.8_254'], title = 'pH7.8 nCL: Normalisation Effects', ylabel = 'Log2(Intensity)', palette = cpal['Set3_qual'])
No weird sample variations
No outrageous normalisation adjustments
Functions
jwrangle.MQ_poolDataByCondition( )
jvis.BoxPlotByColumn_sbplot( )
Next we will compare intensity and sequence coverage between groups. Log2 transformation has already been performed so we need only use jwrangle.MQ_poolDataByCondition( ) to create the appropriate long form dataset for plotting with jvis.BoxPlotByColumn_sbplot( ).
#### Pool data into a single long form dataset
pooled_dfDropGroupOne = jwrangle.MQ_poolDataByCondition(pGroup_log2, metadata_sort, prefix_list = ['Intensity', 'Sequence coverage'])
#### Compare Intensity distribution using a box and whisker plot
sns.set_style('whitegrid')
jvis.BoxPlotByColumn_sbplot(pooled_dfDropGroupOne, 'Intensity: ', 'Intensity')
#### Compare Sequence coverage using a box and whisker plot
sns.set_style('whitegrid')
jvis.BoxPlotByColumn_sbplot(pooled_dfDropGroupOne, 'Sequence coverage: ', 'Sequence coverage %')
These results are consistent with expectations.
Functions
jinspect.MQ_getSumBySample( )
jvis.BarPlotByGroup_sbplot( )
To sum the total peptides observed across all proteins use _jinspect.MQgetSumBySample( ). These sums will be returned as a modified metadata table.
Plotting these by group is easily done with jvis.BarPlotByGroup_sbplot( ). The plotting order is determined by the metadata ordering.
In this case we are inspecting the number of peptides detected after having removed contaminants- thus if some spike-in proteins were removed, i.e. in this case RNAse treatments, they will not contribute to the peptide count. To look at the replicability of these spike-ins, we would reach back to the 'df_droprows' table generated by jinspect.MQ_dropDuplicateIDs( ) in section 7.
#### Extract the total peptides observed per sample
metaStats = jinspect.MQ_getSumBySample(pGroup_log2, metadata_sort, freqList = ['Peptides'], measure = False)
metaStats
#### Plot the sum peptides
sns.set_style('whitegrid')
jvis.BarPlotByGroup_sbplot(metaStats, x_col = 'condition', y_col = 'Peptides', title = 'Sum Peptides vs pH enrichment', pal = set2_paired,
errorbars = 'SEM')
Interesting that recovery from the interphase is linearly associated with increasing pH.
The OdT hybridisation should not have been affected- the hybridisation conditions were similarly balanced after interphase recovery.
Functions
jinspect.MQ_getFrequencyBySample( )
One gene can encode for many proteins that often share regions of similarity. As for illumina-based RNA-Seq, however, shotgun proteomics can rarely assign a peptide species to a singular protein. In MaxQuant these are called proteinGroups. Because we have do not require protein-specific results, and gene identity is more stable, our gene count describes the groups to which our detected proteins have been be assigned. Thus gene here is being detected by protein product, just as it would be detected by RNA product in RNA Seq; none of these 3 are synonymous. To be clear, this is a count and not a measure.
Gene frequency is defined by the summed observations per protein regardless of intensity value and this data is extracted to our modified metadata with jinspect.MQ_getFrequencyBySample( ) .
A typical MQ search will yield identical protein counts (though different values) for Intensity and iBAQ*. LFQ frequencies will vary depending on the search settings:
Notes
* Why protein counts should be identical I don't know. The original iBAQ paper stipulates rules for the inclusion of a protein in the iBAQ calculation but MaxQuant doesn't seem to apply them.
** Previously I tested LFQ min ratio at 1 peptide. At 1 minimum peptide there was unexpected QC clustering. Possible explanations for this are explained in section 7 and are cleaned up by jinspect.MQ_dropDuplicateIDs( ) function. We can expect this function to greatly reduce qualifying IDs (~20% fewer), especially in the QE samples, but I think the trade-off is worth it because we gain 1) a more robust ID check and 2) the same search can be used for LFQ based checks of dynamic changes, i.e. comparing more than one group of cCL captures for biological changes.
#### Count the number of unique
metaStats = jinspect.MQ_getFrequencyBySample(pGroup_log2, metaStats, freqList = ['Intensity', 'iBAQ', 'LFQ intensity'], measure = False)
metaStats
#### Plot the counts
sns.set_style('whitegrid')
jvis.BarPlotByGroup_sbplot(metaStats, x_col = 'condition', y_col = 'Intensity', title = '# Genes Detected By Group', pal = set2_paired, ylabel = 'Unique Genes', errorbars = 'SEM')
This experiment tested the effect of pH variation on the subsequent Qdt-mediated capture of RNP from the interphase
Functions
jwrangle.MQ_getSliceByPrefix( )
jvis.showPearsonRegression_altair( )
The function _jwrangle.MQgetSliceByPrefix( ) provides a convenient means of extracting values of a specific group.
We can then use _jvis.showPearsonRegressionaltair( ) to perform pairwise comparisons between each member of those groups. This function is specifically applied to genes with shared intensities- genes exclusive to one sample or the other, represented by vertical or horizontal datapoints, are plotted but excluded from the pearson calculation.
#### Extract the intensity values as a dictionary where keys = groups
Intensity_Dict = jwrangle.MQ_getSliceByPrefix(pGroup_log2, metadata, 'Intensity', group = 'condition', add_col = None)
Intensity_Dict.keys()
#### Check replicate consistency across all within group pairs
jvis.showPearsonRegression_altair(Intensity_Dict['pH4.5_nCL'], mark_color = set2_paired[2])
jvis.showPearsonRegression_altair(Intensity_Dict['pH4.5_254'], mark_color = set2_paired[2])
jvis.showPearsonRegression_altair(Intensity_Dict['pH5.5_nCL'], mark_color = set2_paired[4])
jvis.showPearsonRegression_altair(Intensity_Dict['pH5.5_254'], mark_color = set2_paired[4])
jvis.showPearsonRegression_altair(Intensity_Dict['pH7.8_nCL'], mark_color = set2_paired[6])
jvis.showPearsonRegression_altair(Intensity_Dict['pH7.8_254'], mark_color = set2_paired[6])
Replicates look good among 254nm cCL samples. More varied among the sparse nCL samples which should be expected.
Functions
jinspect.MQ_getFrequencyByGroup()
jtest.MQ_applyClassifyRBP()
Before classifying our RBP we need to first tally the frequency with which each protein appears in each condition using _jinspect.MQgetFrequencyByGroup( )
Once done, we use _jtest.MQapplyClassifyRBP( ) to generate a dictionary from which each class can be reviewed or plotted.
#### Use the metadata and proteinGroups tables to count how many times a gene is identified in its group (/6).
#### Here I demonstrate how we can count for all instances of Intensity, iBAQ and LFQ Intensity
pGroup_Freq = jinspect.MQ_getFrequencyByGroup(pGroup_log2, metadata, 'iBAQ', group = 'condition')
pGroup_Freq = jinspect.MQ_getFrequencyByGroup(pGroup_Freq, metadata, 'LFQ intensity', group = 'condition')
pGroup_Freq = jinspect.MQ_getFrequencyByGroup(pGroup_Freq, metadata, 'Intensity', group = 'condition')
pGroup_Freq[['ENTREZGENE_gPro primary'] + [i for i in pGroup_Freq.columns if 'Freq' in i]].head(2)
#### Now we can classify RBP; the console will report if all proteins/genes have been properly classified or not.
RBP_Dict_pH4 = jtest.MQ_applyClassifyRBP(pGroup_Freq, 'LFQ intensity', metadata, 'pH4.5', 'pH4.5_nCL', 'pH4.5_254', 3,
add_cols = ['ENTREZGENE_gPro all', 'ENTREZGENE_gPro primary', 'ENTREZGENE_gPro name'])
RBP_Dict_pH5 = jtest.MQ_applyClassifyRBP(pGroup_Freq, 'LFQ intensity', metadata, 'pH5.5', 'pH5.5_nCL', 'pH5.5_254', 3,
add_cols = ['ENTREZGENE_gPro all', 'ENTREZGENE_gPro primary', 'ENTREZGENE_gPro name'])
RBP_Dict_pH7 = jtest.MQ_applyClassifyRBP(pGroup_Freq, 'LFQ intensity', metadata, 'pH7.8', 'pH7.8_nCL', 'pH7.8_254', 3,
add_cols = ['ENTREZGENE_gPro all', 'ENTREZGENE_gPro primary', 'ENTREZGENE_gPro name'])
#### The results of this classifcation can be found in a dictionary of dataframes for each output
#### See help() for an explanation of each dataset
RBP_Dict_pH7.keys()
#### We want the most general overview which of our classes per treatment and so concatenate the results from each Summary_df_annStatus
RBP_Class = pd.concat([RBP_Dict_pH4['Summary_df_annStatus'], RBP_Dict_pH5['Summary_df_annStatus'], RBP_Dict_pH7['Summary_df_annStatus']], axis=0, join='outer')
#### And represent them in a barplot
from matplotlib import pyplot as plt
plt.figure('rbp class')
sns.set_style('whitegrid')
ax = sns.countplot(x='MQgroup', hue = 'RBP Class', data=RBP_Class, palette = cpal['RBP_Class'], edgecolor = 'black')
ax.set_ylabel('Unique Gene Count')
ax.set_title('Unique Genes detected per RBP Class')
RBP_Class.head(1)
#### If we are to look more closely at Summary_df_annStatus we can see it includes the subclasses of the RBP class 2 group
RBP_Dict_pH4['Summary_df_annStatus'].head(10)
#### Because each subclass of the class II RBP are identified based on different statistical assumptions we can more closely inspect if those assumptions trend differently among the different pH treatments.
plt.figure('rbp class')
sns.set_style('whitegrid')
ax = sns.countplot(x='MQgroup', hue = 'RBP subClass', data=RBP_Class[RBP_Class['RBP subClass']!=''].sort_values(by=['MQgroup','RBP subClass']), palette = cpal['Set3_qual'], edgecolor = 'black')
ax.set_ylabel('Unique Gene Count')
ax.set_title('Unique Genes detected per RBP Class')
RBP_Class.head(1)
The number of class I binders rises steadily from pH 4.5 < pH 5.5 < pH 7.8.
Between classes I, II, NC the overwhleming majority of proteins in all treatment conditions are identified as high confidence, class I binders.
There is an interesting distribution difference of Class II subclasses between pH 4.5 + pH 7.8 vs pH 5.5. This differences includes a majority landing in the IIb category. These are for proteins detected in all cCL samples but also n=1 nCL sample. The reason for this difference is not clear but should be monitored in expt.297 to see if the same trend is confirmed.
Here we use the dictionaries output by jtest.MQ_applyClassifyRBP( ) for the purposes of creating a Venn Diagram.
from matplotlib import pyplot as plt
import numpy as np
from matplotlib_venn import venn3, venn3_circles
plt.figure(figsize=(6,6))
v = venn3([set(RBP_Dict_pH4['I']['ENTREZGENE_gPro primary']),
set(RBP_Dict_pH5['I']['ENTREZGENE_gPro primary']),
set(RBP_Dict_pH7['I']['ENTREZGENE_gPro primary'])],
set_labels = ('pH4.5', 'pH5.5', 'pH7.8'),
alpha = 0.5)
c = venn3_circles([set(RBP_Dict_pH4['I']['ENTREZGENE_gPro primary']),
set(RBP_Dict_pH5['I']['ENTREZGENE_gPro primary']),
set(RBP_Dict_pH7['I']['ENTREZGENE_gPro primary'])], linestyle='dashed')
c[0].set_lw(1.5)
c[0].set_ls('dotted')
c[1].set_lw(1.5)
c[1].set_ls('dotted')
c[2].set_lw(1.5)
c[2].set_ls('dotted')
for text in v.set_labels:
text.set_fontsize(18)
for text in v.subset_labels:
text.set_fontsize(14)
If there was any doubt that the different pH treatments might generate qualitatively different protein sets the near complete overlap shown above would dispel this.
Outwardly it would appear that all Class I identified RBPs fall within the next highest pH group and their total number expands with the same trend.
Functions
jinspect.getIsoelectricPoints( )
jinspect.getIsoelectricPointsByClassDict( )
jwrangle.SplitList( )
Many algorithms exist for the calculation of isoelectric points (pI) by sequence analysis. Rather than calculating this data on the fly, I like to use a precalculated database published by Kozlowski 2016 and provided at isoelectricpointdb.org. This database provides precalculated pIs according to a variety of published models, and also an average pI which spans the most consisten algorithms. The function jinspect.getIsoelectricPointsByClassDict( ) will retrieve, as a list, all pIs associated with the proteins in our Class Dictionaries. The lists include all members of the Majority Protein Group that are associated with the identified gene; thus one gene may return more than one pI. This is a deliberate choice; because shotgun proteomics cannot properly discriminate between protein isoforms one sequence cannot be selected to solely represent a gene wihtout introducing user-bias. The majority protein groups is a best guess of the isoforms present and thus the pIs for each reported.
If users wish to curate their own list for pI reporting they should instead use jinspect.getIsoelectricPoints( ). To do so we'll use jwrangle.SplitList( ) to create a list of proteins from instrument QC data and then retrieve the relevant pI data.
#### Read in isoelectric point database (download from isoelectricpointdb.org)
dfisoelectric_point_database = pd.read_csv(base_path / 'downloads' / 'isoelectric_points' / '180822_HUMAN_isoelectricpointdb-org_edit.csv', index_col=False)
#### Calculate the pIs for every protein detected in each class
RBP_Dict_pH4_pI = jinspect.getIsoelectricPointsByClassDict(RBP_Dict_pH4, dfisoelectric_point_database)
RBP_Dict_pH5_pI = jinspect.getIsoelectricPointsByClassDict(RBP_Dict_pH5, dfisoelectric_point_database)
RBP_Dict_pH7_pI = jinspect.getIsoelectricPointsByClassDict(RBP_Dict_pH7, dfisoelectric_point_database)
#### Inspect the keys for each pI dictionary
RBP_Dict_pH7_pI.keys()
#### For comparison we'll also import a proteins typically found in a whole proteome analysis
#### To do this we'll grab some HeLa digest quality control data from the same instrument these experiments were run on
hela_qc = pd.read_csv(base_path / 'my_resources' / 'instrumentQC' / 'QE_191215' / 'proteinGroups.txt', delimiter='\t',index_col=False)
### Create a new list from the Majority protein IDs and get pIs
hela_qcProt = jwrangle.SplitList(hela_qc['Majority protein IDs'].tolist(), [';','-'], replace = '$&', remove_nonstring_values = True, drop_empty_strings = True)
hela_qc_pI = jinspect.getIsoelectricPoints(hela_qcProt, dfisoelectric_point_database)
hela_qc_pI.head(2)
plt.figure('pH4.5 OdT RBP Classes: Isoelectric Points')
sns.set_style('whitegrid')
ax = sns.kdeplot(hela_qc_pI['Avg_pI'], label = 'Proteome', shade = True, alpha = 0.2)
ax = sns.kdeplot(RBP_Dict_pH4_pI['I_pI'], label = 'Class I')
ax = sns.kdeplot(RBP_Dict_pH4_pI['II_pI'], label = 'Class II')
ax = sns.kdeplot(RBP_Dict_pH4_pI['ND_pI'], label = 'Class ND')
ax.set_title('Isoelectric Point: RBP Class (pH4.5)', size = 16)
plt.ylabel('Density', size = 14)
plt.xlabel('pI', size = 14)
plt.legend()
plt.tight_layout()
sns.despine()
plt.close
plt.figure('pH5.5 OdT RBP Classes: Isoelectric Points')
sns.set_style('whitegrid')
ax = sns.kdeplot(hela_qc_pI['Avg_pI'], label = 'Proteome', shade = True, alpha = 0.2)
ax = sns.kdeplot(RBP_Dict_pH5_pI['I_pI'], label = 'Class I')
ax = sns.kdeplot(RBP_Dict_pH5_pI['II_pI'], label = 'Class II')
ax = sns.kdeplot(RBP_Dict_pH5_pI['ND_pI'], label = 'Class ND')
ax.set_title('Isoelectric Point: RBP Class (pH5.5)', size = 16)
plt.ylabel('Density', size = 14)
plt.xlabel('pI', size = 14)
plt.legend()
plt.tight_layout()
sns.despine()
plt.close
plt.figure('pH7.8 OdT RBP Classes: Isoelectric Points')
sns.set_style('whitegrid')
ax = sns.kdeplot(hela_qc_pI['Avg_pI'], label = 'Proteome', shade = True, alpha = 0.2)
ax = sns.kdeplot(RBP_Dict_pH7_pI['I_pI'], label = 'Class I')
ax = sns.kdeplot(RBP_Dict_pH7_pI['II_pI'], label = 'Class II')
ax = sns.kdeplot(RBP_Dict_pH7_pI['ND_pI'], label = 'Class ND')
ax.set_title('Isoelectric Point: RBP Class (pH7.8)', size = 16)
plt.ylabel('Density', size = 14)
plt.xlabel('pI', size = 14)
plt.legend()
plt.tight_layout()
sns.despine()
plt.close
Here all 3 pH treatments produce the expected bias towards higher pI.
The changing distribution among the ND category as pH increases, however, suggests selectivity bias might exist. Indeed, using pH to separate macromolecules introduces the risk of selectivity bias in the data- especially where isoelectric points are used as evidence of RBP identity.
It is reasonable to assume that the original RIC protocol, being conducted entirely in neutral buffers will most accurately represent the expected pIs of RBPs as a group.
Functions
jwrangle.ListsToDataFrameSets( )
jwrangle.importMixedFiles( )
Comparing RBP candidates to those of other studies often relies on retrieving previously prepared lists and dataframes. For this we can use jwrangle.importMixedFiles() or read them directly from a resources folder (you'll need to set up your own).
After retrieving the relevant lists we can create upsetplots for inspecting data. The function jwrangle.ListsToDataFrameSets() helps here by creating multi index dataframes for plotting.
A number of cells are hashed out below. This is because they focus on once-only data wrangling of published data which, once complete, can be saved locally as a new copy and read in for future work. It is kept in this tutorial as an example of how functions such as jweb.mapAnyID_gPro( ) can be used on third party data.
#### Import the resources directory
# Hentze_2018 = jwrangle.importMixedFiles(base_path / 'downloads' / 'published_data' / '2018_Hentze_Nature_Reviews_s2table')
# Hentze_2018.keys()
#### In this example we want the Human Datasets
# Hentze_2018_Hs = Hentze_2018['Hs.csv']
# Hentze_2018_Hs.head(2)
#### That table produces an ugly import, let's fix up the headers and empty cells
# r1 = Hentze_2018_Hs.columns.tolist()
# r2 = Hentze_2018_Hs.loc[0,:].replace(np.nan, '').tolist()
# r3 = []
# for index, label in enumerate(r1):
# r = label + ' (' + r2[index] + ')'
# r = r.replace(' ()', '')
# r3.append(r)
# Hentze_2018_Hs.columns = r3
# Hentze_2018_Hs = Hentze_2018_Hs.iloc[1:,:13]
# Hentze_2018_Hs.head(2)
#### To ensure naming consistency we will remap the ENSEMBL genes to ENTREZGENE.
#### I've prefer ENTREZGENE because it shares the same conventions as Uniprot, QuickGo, and MaxQuant.
# Hentze_2018_Hs_remap = jweb.mapAnyID_gPro(Hentze_2018_Hs['ID'].tolist(), splitstr = 'nosplit', geneProductType = 'gene',
# gConvertOrganism = 'hsapiens', gConvertTarget = 'ENTREZGENE', writetopath = [cwd, 'Hentze_2018_Hs_remap'], writeTargetsAsList = 'NO')
#### For posterity, let's add the remapped gene names to the original dataframe and save it as an edited copy in our resources folder.
# Hentze_id_map = Hentze_2018_Hs_remap['id_map'].rename(columns={'Query': 'ID'}).drop_duplicates()
# Hentze_2018_Hs_edit = pd.merge(Hentze_2018_Hs, Hentze_id_map, on='ID', how='left')
# Hentze_2018_Hs_edit.to_csv(base_path / 'downloads' / 'published_data' / 'Hentze_2018_Hs_edit.csv', index = False )
# Hentze_2018_Hs_edit.head(2)
#### If not already loaded, read in the remapped resource data
Hentze_2018_Hs_edit = pd.read_csv(base_path / 'downloads' / 'published_data' / 'Hentze_2018_Hs_edit.csv')
#### We'll focus on the HEK293T RBPs identified by Baltz and begin by extracting the Gene names and remapping them to ensure consistency.
Baltz_HEK293_RIC = Hentze_2018_Hs_edit[Hentze_2018_Hs_edit['HEK293-RIC (Hs_Baltz2012)']=='YES']['ENTREZGENE_gPro primary']
#### Create upset plot to inspect overlap between the HEK293T RBPs identified by Baltz, and the class I RBPs discovered by our protocol at different pHs.
import upsetplot as upset
dict_list = {'Baltz_HEK293':list(set(Baltz_HEK293_RIC)),
'pH4.5':list(set(RBP_Dict_pH4['I']['ENTREZGENE_gPro primary'])),
'pH5.5':list(set(RBP_Dict_pH5['I']['ENTREZGENE_gPro primary'])),
'pH7.8':list(set(RBP_Dict_pH7['I']['ENTREZGENE_gPro primary']))}
upsetDF = jwrangle.ListsToDataFrameSets(dict_list)
cols = upsetDF.columns.difference(['gene']).tolist()
group_upsetDF = upsetDF.groupby(cols).size()
plt.figure('Common Class I RBPs')
ax = upset.plot(group_upsetDF,sort_by='cardinality', show_counts = True, facecolor= cpal['RBP_Class'][0], element_size =50)
plt.title('Class I RBPs shared with Baltz', size = 16)
plt.close
#### And what would the result be if we took all RBPs identified across the 7 studies?
dict_list = {'All RIC':list(set(Hentze_2018_Hs_edit['ENTREZGENE_gPro primary'])),
'pH4.5':list(set(RBP_Dict_pH4['I']['ENTREZGENE_gPro primary'])),
'pH5.5':list(set(RBP_Dict_pH5['I']['ENTREZGENE_gPro primary'])),
'pH7.8':list(set(RBP_Dict_pH7['I']['ENTREZGENE_gPro primary']))}
upsetDF = jwrangle.ListsToDataFrameSets(dict_list)
cols = upsetDF.columns.difference(['gene']).tolist()
group_upsetDF = upsetDF.groupby(cols).size()
plt.figure('Common Class I RBPs')
ax = upset.plot(group_upsetDF,sort_by='cardinality', show_counts = True, facecolor= cpal['Set1_qual'][3], element_size =50)
plt.title('Class I RBPs shared with Baltz', size = 16)
plt.close
The majority of our Class I RBPs match those found by Baltz et al. These upsetplots, however can be difficult to intpret.
Let's focus on the following features:
Some are new and some found by Baltz
Functions
jweb.mapAnyID_gPro( )
jinspect.getIsoelectricPoints( )
jwrangle.SplitList( )
jwrangle.importMixedFiles( )
Comparing RBP candidates to those of other studies often relies on retrieving previously prepared lists and dataframes. For this we can use jwrangle.importMixedFiles() or read them directly from a resources folder (you'll need to set up your own).
After retrieving the relevant lists we can create upsetplots for inspecting data. The function jwrangle.ListsToDataFrameSets() helps here by creating multi index dataframes for plotting.
A number of cells are hashed out below. This is because they focus on once-only data wrangling of published data which, once complete, can be saved locally as a new copy and read in for future work. It is kept in this tutorial as an example of how functions such as jweb.mapAnyID_gPro( ) can be used on third party data.
#### Lets also draw the isoelectric profile comparison against Baltz.
#### To do so we'll need to fetch the Unprot protein names and
Baltz_protList = jwrangle.SplitList(Hentze_2018_Hs_edit[Hentze_2018_Hs_edit['HEK293-RIC (Hs_Baltz2012)']=='YES']['ID'].tolist(), [';','-'], replace = '$&', remove_nonstring_values = True, drop_empty_strings = True)
#### Now we'll convert the ENSEMBL IDs from our resource table into Uniprot IDs and save the results locally
# Baltz_HEK293_RICprot = jweb.mapAnyID_gPro(Baltz_protList, splitstr = 'nosplit', geneProductType = 'gene', gConvertOrganism = 'hsapiens', gConvertTarget = 'UNIPROTSWISSPROT', writetopath = [cwd, 'Baltz_HEK293_RICprot'], writeTargetsAsList = 'NO')
#### If not already loaded, read in the mapped data and inspect
Baltz_HEK293_RICprot = jwrangle.importMixedFiles(cwd / 'downloads' / 'Baltz_HEK293_RICprot', dropSuffix = 'yes')
Baltz_HEK293_RICprot['id_map'].head(2)
### Now get pIs
Baltz_HEK293_RICprot = jinspect.getIsoelectricPoints(Baltz_HEK293_RICprot['id_map']['UNIPROTSWISSPROT_gPro primary'].tolist(), dfisoelectric_point_database)
Baltz_HEK293_RICprot.head(2)
#### Now plot the pI comparison vs Class I
plt.figure('RBP purification vs Baltz RIC\nIsoelectric Points')
sns.set_style('whitegrid')
ax = sns.kdeplot(hela_qc_pI['Avg_pI'], label = 'Proteome', shade = True, alpha = 0.2)
ax = sns.kdeplot(RBP_Dict_pH7_pI['I_pI'], label = 'Class I', color = 'green')
# ax = sns.kdeplot(RBP_Dict_pH7_pI['II_pI'], label = 'Class II')
ax = sns.kdeplot(Baltz_HEK293_RICprot['Avg_pI'], label = 'Baltz RIC RBP', color = 'red')
ax.set_title('RBP purification vs Baltz RIC\nIsoelectric Points', size = 16)
plt.ylabel('Density', size = 14)
plt.xlabel('pI', size = 14)
plt.legend()
plt.tight_layout()
sns.despine()
plt.close
Strong agreement between our class I RBP and those of Baltz. Thus while there may not be complete agreement between specific identity, there is total agreement between shared characteristics of the discovered proteins.
Functions
jwrangle.importMixedFiles( )
jweb.fetchQuickGO_stats( )
In this section we will explore Gene Ontology (GO) memberships for the observed proteins. There is little use in applying statistical tests such as Gene Ontology Enrichment Analysis (GOEA) for these experiments; the combination of selection by RNA interaction and the comparative lack of deep RBP validation for many candidates would make such a study rather spurious. We can, however, investigate the frequency with which our identified RBPs appear in previous studies. In addition, we can use this frequency to further assess whether the 20% and 30% capture conditions used here are equivalent or not.
A number of GO-specific and utility functions are provided to help with retrieving Gene Ontologies from the QuickGo database. In this section we'll look at the most basic.
The function jweb.fetchQuickGO_stats( ) will fetch the annotation statistics for all records belonging to the gene ID from a submitted list. These statistics are generally of two types: no. of annotations (which relates to unique proteins) and no. of geneProducts (which relate to the gene count; poorly worded I know). The quality of these records is given by whether identification originates from a SwissPort or a TrEMBL entry. Reviewing these statistics before beginning an analysis is ideal, because it contextualises the breadth of future analyses. This function returns these statistics in the from of a dictionary which can be converted to a dataframe for easier viewing by using the dedicated function jweb.getQuickGO_stats( ).
In addition to contextualising the search space of subsequent analyses, fetching the annotation numbers is important for checking that the number of records, per GO ID, falls below 10000. This is because QuickGo will not allow larger searches to be done programmatically. If your GO ID of interest has many more records users should retrieve their records manually. These details will be covered fourther in the next section.
#### I like to keep a table of interesting GO terms in a local csv file, let's find it
MyResources = jwrangle.importMixedFiles(base_path / 'my_resources')
MyResources.keys()
MyResources['GO_TermsOfInterest.csv'].head(5)
# #### Let's get basic statistics on the all GO IDs listed from depth 3 down"
# MyGO_Stats_Dict = jweb.fetchQuickGO_stats(MyResources['GO_TermsOfInterest.csv']['go ID'].tolist()[3:], QG_geneProductType = 'protein', QG_taxonId = '9606', QG_geneProductSubset = ['Swiss-Prot', 'TrEMBL'])
# #### To view basic information, like the number of annotations associated with the GO term
# MyGO_Stats = jweb.getQuickGO_stats(MyGO_Stats_Dict)
# #### Save a local copy of the stats dataframe
# MyGO_Stats_DF = pd.merge(MyResources['GO_TermsOfInterest.csv'], MyGO_Stats, on = 'go ID', how = 'outer')
# MyGO_Stats_DF.to_csv(cwd / 'downloads' / 'MyGO_Stats_DF.csv', index = False)
# #### View the DataFrame
# MyGO_Stats_DF.head(50)
#### Read a local copy and view DataFrame
MyGO_Stats_DF = pd.read_csv(cwd / 'downloads' / 'MyGO_Stats_DF.csv')
MyGO_Stats_DF.head(50)
We can see that, with the exception of dsDNA binding, the population of members belonging to RNA-binding at depth 5 is quite sparse, especially compared to the depth 4 RNA binding category. mRNA-binding is by far the most populated group, most likely due to influences from previous OdT captures. I would expect, however, that annotations with experimental evidence are likely to be dramatically low- a good indication of the nascent state of RNA-binding protein research and one that should probably be emphasised in a future introduction.
From depth 4 onwards the SwissProt and TrEMBL counts are below 10000 records so, conveniently, we can continue the tutorial with the simplest scenario for record extraction.
Functions
jweb.fetchQuickGO( )
jwrangle.concatGO_DataFrameDict( )
jweb.mapQuickGO( )
We can see above that none of our downloaded IDs have exceeded our fetch limit of 10000 records. If any did, we would need to manually retrieve the tsv file.
For the GO terms we wish to investigate to investigate jweb.fetchQuickGO( ) will fetch the relevant proteins and also apply the same onsistent gene ID mapping algorithm we used earlier when remapping the MaxQuant IDs. This process is important because it allows us to provide consistent gene IDs to subsequent sets analysis. Where the writetopath options is used, the results from any searches will be saved to a local downloads folder- this is useful as a snapshot of the annotations used at the time or as a simple way of avoiding fetching the records via API in the future.
The function jwrangle.concatGO_DataFrameDict( ) let's us concatenate a dictionary created by jweb.fetchQuickGO( ). This is useful when the user wishes to pool both SwissProt and TrEMBL records for a given
A Note on Manual Downloads
The jweb.fetchQuickGO( ) will also output to console the html address that one should use if a manual download if required; this address will encompass all the relevant record characteristics that typically used by this suite. Once this table has been downloaded, the function jweb.mapQuickGO( ) can be used to provide the same ID mapping service as performed in jweb.fetchQuickGO( ). The returned elements will also be manipulated into the same format.
#### Download and create a local copy of all the records associated with our GO query from depth 4 onwards.
# QuickGo_dict = jweb.fetchQuickGO(MyGO_Stats_DF['go ID'][4:], QG_geneProductType = 'protein', QG_taxonId = '9606', QG_geneProductSubset = ['Swiss-Prot', 'TrEMBL'], gConvertOrganism='hsapiens', writetopath= True)
#### To avoid future API requests we will load the saved files....
QuickGo_dict = jwrangle.importMixedFiles(cwd / 'downloads' / 'QuickGo')
#### ....and concatenate all SwissProt and TrEMBL entries into a single dictionary.
QuickGo_dict_concat = jwrangle.concatGO_DataFrameDict(QuickGo_dict)
QuickGo_dict_concat.keys()
All records sucessfully retrieved, saved locally, and a dictionary of concatenated SwissProt and TrEMBL entries has been generated.
Functions
jwrangle.AnnotateDataFrameCtrls( )
jinspect.MQ_getFrequencyBySample( )
The function jwrangle.AnnotateDataFrameCtrls( ) takes our QuickGo records and annotates each protein or gene in a given dataframe (i.e. a proteinGroups table) for membership to the searched GO ID. The function jinspect.MQ_getFrequencyBySample( ) acts similarly to the peptide and gene count functions used earlier- it will sum the frequency of memberships to each GO catgeory and report the counts as a modified metadata table.
#### With our GO records in hand we next investigate whether our identified proteins are members of our GO IDs
#### Let's start by looking at only GO:0003723. First, dedicate a dictionary to this search
dict_GO0003723 = {'GO0003723': QuickGo_dict_concat['GO0003723']}
#### Next, annotate the last version of our modified proteinGroups table
pGroup_GO0003723 = jwrangle.AnnotateDataFrameCtrls(pGroup_Freq, dict_GO0003723, search_match = 'ENTREZGENE_gPro primary', dict_match = 'ENTREZGENE_gPro primary', none_col = 'GO_None')
#### Next find the counts for each GO ID being searched we will modify our metadata table in a fashion in the same way as for prptide and gene counting.
#### We'll use iBAQ for these counts but, given all intensities have previously been filtered by LFQ membership both 'Intensity' or 'LFQ intensity' would give the same result.
metaStatsGO0003723 = jinspect.MQ_getFrequencyBySample(pGroup_GO0003723['ann_df'], metaStats, freqList = list(dict_GO0003723.keys()) + ['GO_None'], measure = 'iBAQ')
#### Now Calculate the % GO0003723 members per group
metaStatsGO0003723['% RBP'] = metaStatsGO0003723.apply(lambda row: round(100*row['GO0003723']/(row['GO0003723']+row['GO_None'])), axis = 1)
#### Plot
jvis.BarPlotByGroup_sbplot(metaStatsGO0003723, x_col = 'condition', y_col = '% RBP', title = 'GO:0003723, RNA-Binding', pal = set2_paired, yrange = [0,110])
Between 80% - 100% of each capture represents known RNA-binding proteins at pH 4.5 > pH5.5 > pH 7.8. A cursory analysis might take the view the pH 4.5 is best because this % is closest to 100%. We must remember that this % is calculated only on previously reported RBPs. Thus the pH7.8 group might:
Functions
jwrangle.AnnotateDataFrameCtrls( )
jinspect.MQ_getFrequencyBySample( )
jinspect.MQ_getMeans( )
The function jwrangle.AnnotateDataFrameCtrls( ) takes our QuickGo records and annotates each protein or gene in a given dataframe (i.e. a proteinGroups table) for membership to the searched GO ID. The function jinspect.MQ_getFrequencyBySample( ) acts similarly to the peptide and gene count functions used earlier- it will sum the frequency of memberships to each GO catgeory and report the counts as a modified metadata table. Finally, the function jinspect.MQ_getMeans( ) will make it easy for us to calculate the means across any specific group in our metadata; essentially it acts like a native python 'groupby'.
#### Let's create a QuickGo dictionary of proteins/genes with nucleic acid binding properties (depth 5). These have been marked as 'general' under the 'ctrl list type' column of our GO_stats dataframe.
list_NA = MyGO_Stats_DF[MyGO_Stats_DF['ctrl list type']=='general']['go ID'].apply(lambda x: x.replace(':','')).tolist()
dict_NA = {}
for key, value in QuickGo_dict_concat.items():
if key in list_NA:
dict_NA[key] = value
#### Next, annotate the last version of our modified proteinGroups table
pGroup_NA = jwrangle.AnnotateDataFrameCtrls(pGroup_Freq, dict_NA, search_match = 'ENTREZGENE_gPro primary', dict_match = 'ENTREZGENE_gPro primary', none_col = 'GO_None')
#### Next find the counts for each GO ID being searched we will modify our metadata table in a fashion in the same way as for prptide and gene counting.
#### We'll use LFQ intensity for these counts but, given all intensities have previously been filtered by LFQ membership both 'Intensity' or 'iBAQ' would give the same result.
metaStats_NA = jinspect.MQ_getFrequencyBySample(pGroup_NA['ann_df'], metaStats, freqList = list(dict_NA.keys()) + ['GO_None'], measure = 'LFQ intensity')
#### Calculate the means for our selected groups
means_NA = jinspect.MQ_getMeans(metaStats_NA, [i for i in metaStats_NA.columns if 'GO' in i], group = 'condition')
#### Relabel the GO IDs with names to make reading easier
MyGO_IDs = dict(zip([i.replace(':','') for i in MyGO_Stats_DF['go ID'].tolist()], MyGO_Stats_DF['GO Term']))
col_names = []
for i in list(means_NA.columns):
if 'GO0' in i:
for key, value in MyGO_IDs.items():
if key in i:
col_names.append(i.replace(key, value))
else:
col_names.append(i)
means_NA.columns = col_names
means_NA
#### Use the native method .stack() to create a DataFrame for the stakced histogram
means_NA_stack = means_NA.stack().reset_index()
means_NA_stack.columns=['condition', 'GO code', 'mean count']
means_NA_stack = means_NA_stack.sort_values(['condition'])
means_NA_stack.head(3)
#### Chart Nucleic Acid GO memberships in a stacked histogram
chart = alt.Chart(means_NA_stack
).mark_bar(cornerRadiusBottomRight=0, cornerRadiusTopRight=0, stroke='black', fillOpacity=0.7, strokeWidth=0.5,
).encode(x='sum(mean count):Q', y='condition:N', color=alt.Color('GO code:N', scale=alt.Scale(scheme='Set3'))
).properties(height=200, width=400, title = 'GO memberships: Nucleic Acids')
chart.configure_title(fontSize = 15, fontWeight='normal'
).configure_axis(labelFontSize=14, labelFontWeight='normal', titleFontSize = 14, titleFontWeight='normal'
).configure_legend(titleFontSize = 14, titleFontWeight='normal', symbolStrokeWidth = 0.5, labelFontSize = 13)
The counts are dominated by RNA binders, with some DNA binders present. Given the overall % RNA binders is very high, however, we can presume that these DNA binders are proteins that likely can also bind RNA. This is reinforced by the lack of DNA binders being present in the non-crosslinked samples.
The pH7.8 protocol appears ideal:
This tutorial notebook will end here. Further functions available in RBP Suite will be explored in other notebooks.